
#include "lmexxx_conf.h"

#define BLOCKING_SEND_QUEUE_SIZE		16
#define BLOCKING_TIME_TICK_MS			100

typedef struct{
	uint8_t* msg;
	uint16_t msg_len;
	uint16_t blocking_time_tick;
}BLOCKING_SEND_ITEM_STRUCT;

static QueueHandle_t blocking_send_queue = NULL;
static uint8_t blocking_send_timer = 0xff;

extern void blocking_send_send_hook(uint8_t* msg, uint16_t msg_len);

uint8_t blocking_send_send(uint8_t* msg, uint16_t msg_len, uint16_t blocking_time_tick)
{
	BLOCKING_SEND_ITEM_STRUCT item;

	if(blocking_send_queue == NULL || blocking_send_timer == NULL){
		return 0;
	}

	if(0 == APP_CheckGenTimerRunning(blocking_send_timer)){
		if(blocking_time_tick > 0){
			APP_SetGenTimer(blocking_send_timer, blocking_time_tick*BLOCKING_TIME_TICK_MS);
			APP_StartGenTimer(blocking_send_timer);	
		}
		blocking_send_send_hook(msg, msg_len);
	}
	else{
		item.msg = msg;
		item.msg_len = msg_len;
		item.blocking_time_tick = blocking_time_tick;
		if(pdPASS != xQueueSendToBack(blocking_send_queue, &item, 1000)){
			return 0;
		}
	}

	return 1;
}

static void blocking_send_timer_handler(void)
{
	BLOCKING_SEND_ITEM_STRUCT item;

	APP_StopGenTimer(blocking_send_timer);
	if(pdPASS == xQueueReceive(blocking_send_queue, &item, 1000)){
		APP_SetGenTimer(blocking_send_timer, item.blocking_time_tick*BLOCKING_TIME_TICK_MS);
		APP_StartGenTimer(blocking_send_timer);
		blocking_send_send_hook(item.msg, item.msg_len);
	}
}

uint8_t blocking_send_init(void)
{
	if(blocking_send_queue == NULL){
		blocking_send_queue = xQueueCreate((UBaseType_t)BLOCKING_SEND_QUEUE_SIZE, sizeof(BLOCKING_SEND_ITEM_STRUCT));
		if(blocking_send_queue == NULL){
			return 0;
		}
	}
	if(blocking_send_timer == 0xff){
		blocking_send_timer = APP_NewGenTimer(BLOCKING_TIME_TICK_MS, blocking_send_timer_handler);
		if(blocking_send_timer == 0xff){
			return 0;
		}
	}
	return 1;
}

